<template>
  <div class="app-container">
    <el-form ref="filterForm" :inline="true" :model="listQuery" class="filter-container">
      <el-form-item prop="id">
        <el-input v-model="listQuery.id" size="small" placeholder="ID" clearable style="width: 100px;" @keyup.enter.native="handleFilter" />
      </el-form-item>
      <el-form-item prop="title">
        <el-input v-model="listQuery.title" size="small" placeholder="标题" clearable style="width: 200px;" @keyup.enter.native="handleFilter" />
      </el-form-item>

      <el-form-item prop="fieldid">
        <el-select
          v-model="listQuery.fieldid"
          size="small"
          filterable
          clearable
          placeholder="所属分类"
          style="width: 200px"
          @change="handleFilter"
        >
          <el-option
            v-for="item in fieldOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="state">
        <el-select v-model="listQuery.state" size="small" placeholder="是否上线" clearable style="width: 110px" @change="handleFilter">
          <el-option v-for="item in stateOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item prop="share">
        <el-select v-model="listQuery.share" size="small" placeholder="可分享" clearable style="width: 110px" @change="handleFilter">
          <el-option v-for="item in shareOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item prop="powerid">
        <el-select v-model="listQuery.powerid" size="small" placeholder="权限" clearable style="width: 110px" @change="handleFilter">
          <el-option v-for="item in powerOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleFilter">筛选</el-button>
        <el-button size="small" @click="resetFilter">重置</el-button>
        <el-button
          size="small"
          type="success"
          icon="el-icon-plus"
          @click="toArticleNew"
        >添加文章</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="位置" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.place }}
        </template>
      </el-table-column>
      <el-table-column label="文章标题">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="封面" width="150" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.cover" alt="" width="100%">
        </template>
      </el-table-column>
      <el-table-column label="作者" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.author }}
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.fieldList"
            :key="item.id"
            effect="plain"
            type="success"
            size="mini"
          >{{ item.name + '--' + item.typename }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限" align="center">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.powerList"
            :key="item.id"
            effect="plain"
            size="mini"
          >{{ item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="已上线" width="80" align="center">
        <template slot-scope="scope">
          <i v-if="scope.row.state === 1" class="el-icon-check text-success" />
          <i v-else class="el-icon-close text-warning" />
        </template>
      </el-table-column>
      <el-table-column label="可分享" width="80" align="center">
        <template slot-scope="scope">
          <i v-if="scope.row.share === 1" class="el-icon-check text-success" />
          <i v-else class="el-icon-close text-warning" />
        </template>
      </el-table-column>
      <el-table-column label="创建于" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.publishtime | moment('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <el-button
              size="small"
              plain
            >操作 <i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="toArticleEdit(scope.row.id)"
              >编辑</el-dropdown-item>
              <el-dropdown-item
                divided
                @click.native="setTop(scope.row.id)"
              >置顶</el-dropdown-item>
              <el-dropdown-item
                @click.native="moveUp(scope.row.id)"
              >上移</el-dropdown-item>
              <el-dropdown-item
                @click.native="moveDown(scope.row.id)"
              >下移</el-dropdown-item>
              <el-dropdown-item
                @click.native="setBottom(scope.row.id)"
              >置底</el-dropdown-item>
              <el-dropdown-item
                divided
                @click.native="removeArticle(scope.row.id)"
              >
                <span class="text-danger">删除</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="fetchData" />
  </div>
</template>

<script>
import {
  getCategories,
  getArticles,
  removeArticle,
  articleSetTop,
  articleSetBottom,
  articleMoveUp,
  articleMoveDown
} from '@/api/articles'
import { getUserState } from '@/api/baseData'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import {
  formatQuery
} from '@/utils'

export default {
  name: 'ArticlesList',
  components: {
    Pagination
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        id: formatQuery(this.$route.query.id, false),
        title: formatQuery(this.$route.query.title, false),
        fieldid: formatQuery(this.$route.query.fieldid, true),
        powerid: formatQuery(this.$route.query.powerid, true),
        state: formatQuery(this.$route.query.state, true),
        share: formatQuery(this.$route.query.share, true),
        page: 1,
        size: 30
      },
      fieldOptions: [],
      stateOptions: [
        {
          label: '是',
          key: 1
        },
        {
          label: '否',
          key: 0
        }
      ],
      shareOptions: [
        {
          label: '是',
          key: 1
        },
        {
          label: '否',
          key: 0
        }
      ],
      powerOptions: []
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  // watch: {
  //   $route: {
  //     handler(route) {
  //       if (!this._.isNil(route.query.page) &&
  //         !this._.isEmpty(route.query.page)
  //       ) {
  //         this.listQuery.page = parseInt(route.query.page)
  //       } else {
  //         this.listQuery.page = 1
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    if (!this._.isNil(this.$route.query.page) &&
      !this._.isEmpty(this.$route.query.page)
    ) {
      this.listQuery.page = parseInt(this.$route.query.page)
    } else {
      this.listQuery.page = 1
    }
    this.fetchUserState()
    this.fetchFieldList()
    this.fetchData()
  },
  methods: {
    fetchUserState() {
      getUserState().then(response => {
        // console.log(response)
        this.powerOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchFieldList() {
      getCategories().then(response => {
        // console.log(response)
        this.fieldOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData() {
      this.listLoading = true
      const query = {
        ...this.$route.query,
        ...this.listQuery
      }
      this.$router.push({
        query
      }).catch(err => {
        console.log(err)
      })
      getArticles(this.listQuery).then(response => {
        // console.log(response)
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    removeArticle(id) {
      const userid = this.id
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeArticle({ id, userid }).then(response => {
          // console.log(response)
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.fetchData()
    },
    resetFilter() {
      this.$refs.filterForm.resetFields()
      for (const i in this.listQuery) {
        if (i !== 'size') {
          this.listQuery[i] = undefined
        }
      }
      // console.log(this.listQuery)
      this.$router.push({
        query: {
          page: 1
        }
      }).catch(err => {
        console.log(err)
      })
      this.handleFilter()
    },
    toArticleNew() {
      this.$router.push('/articles/new')
    },
    toArticleEdit(id) {
      this.$router.push(`/articles/edit/${id}`)
    },
    setTop(id) {
      articleSetTop({ id }).then(response => {
        // console.log(response)
        if (response.rtncode === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: '操作失败，请稍后再试!'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    setBottom(id) {
      articleSetBottom({ id }).then(response => {
        // console.log(response)
        if (response.rtncode === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: '操作失败，请稍后再试!'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    moveUp(id) {
      articleMoveUp({ id }).then(response => {
        // console.log(response)
        if (response.rtncode === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: '操作失败，请稍后再试!'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    moveDown(id) {
      articleMoveDown({ id }).then(response => {
        // console.log(response)
        if (response.rtncode === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: '操作失败，请稍后再试!'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
